package com.woniuxy.config;

import com.woniuxy.util.JwtUtil;
import com.woniuxy.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI()+"前置处理");
        String accessToken = request.getHeader("accessToken");
        if(accessToken ==null){
//            throw new Exception("还未登录");
        }else {
           try {
               JwtUtil.parseToken(accessToken);
           }catch (ExpiredJwtException e){
               String refreshToken = redisUtil.getString(accessToken);
               if(refreshToken==null){
                   throw e;
               }else{
                    //签发token
                   Claims claims = JwtUtil.parseToken(refreshToken);
                   Object userId = claims.get("userId");
                   HashMap<String, Object> body = new HashMap<>();
                   body.put("sub",userId);
                   String newAccessToken = JwtUtil.createToken(body, 30);
                   String newRefreshToken = JwtUtil.createToken(body,24*60);
                   //重新存入redis
                   redisUtil.setString(newAccessToken,newRefreshToken,24*60*60);
                   //返回给前端
                   response.setHeader("accessToken",newAccessToken);
               }
           }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String accessToken = request.getHeader("accessToken");
        if (accessToken!=null){
            try {
                JwtUtil.parseToken(accessToken);
            }catch (ExpiredJwtException e){
                redisUtil.delete(accessToken);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptorl>>>afterCompletion");
    }
}
